package com.cet.designapplication.visitor;

import com.cet.designapplication.composite.AbstractProductItem;
import com.cet.designapplication.composite.ProductComposite;
import com.cet.designapplication.utils.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author NSOC
 */

@Component
public class DelItemVisitor implements ItemVisitor<AbstractProductItem> {

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @Override
    public AbstractProductItem visit(AbstractProductItem productItem) {

        ProductComposite removeItem = (ProductComposite) productItem;
        ProductComposite currentItem = (ProductComposite) redisCommonProcessor.get("items");
        if (removeItem.getPid() == currentItem.getId()) {
            currentItem.delProductChild(removeItem);
            return currentItem;
        }

        removeChild(currentItem, removeItem);
        return currentItem;
    }

    private void removeChild(ProductComposite currentItem, ProductComposite removeItem) {
        for (AbstractProductItem abstractProductItem : currentItem.getChild()) {
            ProductComposite item = (ProductComposite) abstractProductItem;
            if (item.getId() == removeItem.getPid()) {
                item.delProductChild(removeItem);
                break;
            } else {
                removeChild(item, removeItem);
            }
        }
    }
}
